import 'dart:math' as math;

import 'package:demo/constants/app_icon.dart';
import 'package:demo/pages/category_page.dart';
import 'package:demo/pages/home_page.dart';
import 'package:demo/pages/shopping_cart_page.dart';
import 'package:demo/provider/view_model/root_view_model.dart';
import 'package:demo/provider/widget/base_provider_widget.dart';
import 'package:flutter/material.dart';

/// tabicon的数据源
class TabIconData {
  TabIconData(this.title, this.iconPath, this.selectedIconPath, this.index);

  IconData iconPath;
  String title;
  IconData selectedIconPath;
  int index;
}

class RootPage extends StatefulWidget {
  @override
  _RootViewState createState() => _RootViewState();
}

class _RootViewState extends State<RootPage> {
  /// pageview控制器
  late final PageController _pageController;

  /// view_model
  late final RootViewModel _rootViewModel;

  /// 页面组
  final Map<int, Widget> _pageGroup = {
    0: HomePage(),
    1: CategoryPage(),
    2: ShoppingCartPage(),
    3: HomePage(),
  };

  /// icon数据
  final List<TabIconData> _groupData = [
    TabIconData("首页", home, home_s, 0),
    TabIconData("分类", category, category_s, 1),
    TabIconData("活动", category, category_s, -1),
    TabIconData("购物车", shoppingCart, shoppingCart_s, 2),
    TabIconData("我的", my, my_s, 3),
  ];

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
    _rootViewModel = RootViewModel();
  }

  @override
  void dispose() {
    _pageController.dispose();
    _rootViewModel.dispose();
    super.dispose();
  }

  /// 切换对应的tab
  void _onChangeTabItemListener(TabIconData g) {
    if (g.index == -1) {
      return;
    }
    if (_pageController.page != g.index) {
      _pageController.jumpToPage(g.index);
      _rootViewModel.tabIndex = g.index;
    }
  }

  /// 构建底部tab item
  Widget _buildTabItem(TabIconData tabIconData, double itemW) {
    return GestureDetector(
      onTap: () => _onChangeTabItemListener(tabIconData),
      child: Container(
        height: kBottomNavigationBarHeight,
        width: itemW,
        color: Colors.white,
        child: Selector<RootViewModel, int>(
          shouldRebuild: (int previous, int next) {
            // 只要求更新对应的2个
            return previous == tabIconData.index || next == tabIconData.index;
          },
          builder: (BuildContext context, int value, Widget? child) {
            IconData iconPath = tabIconData.iconPath;
            Color iconTextColor = Color(0xffAAAAAA);
            Color? iconColor;
            if (value == tabIconData.index) {
              iconPath = tabIconData.selectedIconPath;
              iconTextColor = Colors.red;
              iconColor = Colors.red;
            }
            return Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Icon(iconPath, size: 22, color: iconColor),
                Text(
                  tabIconData.title,
                  style: TextStyle(fontSize: 10, color: iconTextColor),
                ),
              ],
            );
          },
          selector: (BuildContext p1, RootViewModel p2) => p2.tabIndex,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final double tabItemW = MediaQuery.of(context).size.width / 5;
    return BaseProviderWidget<RootViewModel>(
      viewModel: _rootViewModel,
      child: Scaffold(
        body: PageView.builder(
          controller: _pageController,
          itemBuilder: (BuildContext context, int index) {
            if (_pageGroup.containsKey(index)) {
              return _pageGroup[index]!;
            }
            return const SizedBox();
          },
          pageSnapping: true,
          physics: NeverScrollableScrollPhysics(),
          itemCount: 4,
        ),
        bottomNavigationBar: SizedBox(
          height: kBottomNavigationBarHeight + MediaQuery.of(context).padding.bottom,
          child: PhysicalShape(
            color: Colors.white,
            elevation: 8,
            clipper: _TabClipper(radius: 30),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                for (TabIconData g in _groupData) _buildTabItem(g, tabItemW),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

/// 绘画凸起的底部
class _TabClipper extends CustomClipper<Path> {
  _TabClipper({this.radius = 38.0});

  final double radius;
  final double oneHundredAndEightyPi = math.pi / 180;

  @override
  Path getClip(Size size) {
    final Path path = Path();
    final double left = (size.width / 2) - radius / 2;
    path.arcTo(Rect.fromLTWH(left - 7.5, -radius / 2, radius + 15, radius + 15), degreeToRadians(-180),
        degreeToRadians(180), false);
    path.addRect(Rect.fromLTWH(0, 0, size.width, size.height));
    path.close();
    return path;
  }

  @override
  bool shouldReclip(_TabClipper oldClipper) => false;

  double degreeToRadians(double degree) => oneHundredAndEightyPi * degree;
}
